package com.avic.map.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URL;

/**
 * @Description
 * @Author huangsheng
 * @Date 2018/10/23 11:40
 */
@Slf4j
public class GetLocationUtil {

    private static final String URL_STRING = "http://gc.ditu.aliyun.com/regeocoding?l=%s,%s&type=010";

    public static String getAdd(BigDecimal log, BigDecimal lat) {
        BufferedReader in = null;
        String result = StringUtils.EMPTY;
        //lat 小 log 大
        //参数解释: 纬度,经度 type 001 (100代表道路，010代表POI，001代表门址，111可以同时显示前三项)
        String urlString = String.format(URL_STRING, lat, log);
        try {
            URL url = new URL(urlString);
            java.net.HttpURLConnection conn = (java.net.HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setConnectTimeout(2000);
            conn.setRequestMethod("POST");
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONArray jsonArray = JSONArray.parseArray(jsonObject.getString("addrList"));
            JSONObject j_2 = JSONObject.parseObject(jsonArray.get(0).toString());
            String admName = j_2.getString("admName");
            String name = j_2.getString("name");
            return admName + name;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return StringUtils.EMPTY;
    }
}
